﻿using Daemon.Service.Contract;
using Daemon.Model;
using Microsoft.AspNetCore.Http;
using System.Linq;
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Daemon.Repository.Contract;
using Daemon.Common.Tree;
namespace Daemon.Service
{
    public class AttachmentTreeService : IAttachmentTreeService
    {
        private readonly IAttachmentTreeRepository _attachmentTreeRepository;
        public AttachmentTreeService(IAttachmentTreeRepository attachmentTreeRepository)
        {
            _attachmentTreeRepository = attachmentTreeRepository;
        }

        public List<TreeNode<AttachmentTree>> GetAttachmentTree()
        {
            var attachmentTreeList = _attachmentTreeRepository.FindAll().ToList();
            var treeResult = new TreeFactory<AttachmentTree>(Compare).CreateTreeByLevel(attachmentTreeList);
            return treeResult;
        }

        private TeeNodeCompareResult Compare(AttachmentTree obj1, AttachmentTree obj2)
        {
            if (obj1.Code == obj2.Code)
                return TeeNodeCompareResult.EqualNode;
            if (obj1.Code.Length > obj2.Code.Length)
            {
                if (obj1.Code.IndexOf(obj2.Code) == 0)
                    return TeeNodeCompareResult.Child;
                else
                    return TeeNodeCompareResult.NexLevelNode;
            }
            else if (obj1.Code.Length < obj2.Code.Length)
                return TeeNodeCompareResult.Parent;
            else if (obj1.Code.CompareTo(obj2.Code) < 0)
                return TeeNodeCompareResult.PreNode;
            else
                return TeeNodeCompareResult.NextNode;
        }
    }
}
